package com.ruoyi.util.jwt;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.global.CustomException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.web.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
public class SecurityUtils {
    /**
     * 请求头里携带的 key
     */
    public static UserRequestBaseInfo getRequestHead() {
        UserRequestBaseInfo entity = getUserBaseRequestHead();
        if (ObjectUtils.isEmpty(entity)){
            throw new CustomException("请求头对象为空");
        }
        return entity;
    }


    /**
     * 从当前线程请求里直接取 openid（拦截器里已经 set 过）
     */
    private static UserRequestBaseInfo getUserBaseRequestHead() {
        ServletRequestAttributes attrs =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attrs == null) {
            // 非 web 环境（定时任务、异步线程）
            return null;
        }
        HttpServletRequest request = attrs.getRequest();
//        String requestURI = request.getRequestURI();
        String openId = (String) request.getAttribute("openid");
        String tenantId = (String) request.getAttribute("tenantId");
        return UserRequestBaseInfo.builder().openId(openId).tenantId(tenantId).build();
    }

    public static String getOpenidFromLoginUser() {
        try {
            LoginUser loginUser = SpringUtils.getBean(TokenService.class)
                    .getLoginUser(ServletUtils.getRequest());
            return loginUser == null ? null : loginUser.getUsername(); // 存的就是 openid
        } catch (Exception e) {
            log.debug("非小程序端，无 LoginUser");
            return null;
        }
    }
}
